package com.panshi.repast.ImageCache;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Comparator;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.panshi.repast.Util.Base64;
import com.panshi.repast.Util.Utils;

/**
 * 异步缓存文件，SD卡
 * 
 */
public class CacheFileUtil {

	/**
	 * 文件数目
	 */
	private static final int MAX_FILE_NUM = 50;

	private static final int DEFAULT_CACHE_TIME = 24 * 60 * 60 * 1000; // 存储文件时间

	/**
	 * 读取文件 图片
	 * 
	 * @param fileName
	 * @return
	 */
	public static Bitmap loadImageFromFile(String rootDir, String fileName) {
		fileName = encodeByse64(fileName);
		Bitmap bitmap = null;
		if (!Utils.isSDCardEnable()) {
			return null;
		}

		try {
			File file = new File(rootDir, fileName);
			if (!file.exists()) {
				// Log.i("ooooo", "get not: "+(rootDir + fileName));
				return null;
			}
			// bitmap = BitmapFactory.decodeFile(fileName);
			bitmap = BitmapFactory.decodeFile(rootDir + fileName);
		} catch (OutOfMemoryError oom) {
			CacheMemUtil.clearCache();
		} catch (Exception e) {
			Log.e("ooooo", e.toString());
		}

		return bitmap;
	}

	/**
	 * 文件路径
	 * 
	 * @param rootDir
	 * @param fileName
	 * @return
	 */
	public static String getImagePathForRoot(String rootDir, String fileName) {
		fileName = encodeByse64(fileName);
		File file = new File(rootDir, fileName);
		Log.e("ggggg", "imagePath: " + file.getPath());
		return file.getPath();
	}

	/**
	 * 保存到SD卡
	 * 
	 * @param data
	 * @param rootDir
	 * @param fileName
	 * @return
	 */
	public static boolean saveByte2SDCard(byte[] data, String rootDir,
			String fileName) {
		fileName = encodeByse64(fileName);
		/**
		 * SD卡不存在
		 */
		if (!Utils.isSDCardEnable()) {
			return false;
		}
		// Log.d("ooooo", "save: "+(rootDir + fileName));
		BufferedOutputStream fos = null;
		try {

			File file = new File(rootDir, fileName);
			File parent = file.getParentFile();
			if (!parent.exists()) {
				parent.mkdirs();
			}
			file.createNewFile();
			fos = new BufferedOutputStream(new FileOutputStream(file));
			fos.write(data);
			fos.close();
		} catch (Exception e) {
			return false;
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (Exception e) {
				}
			}
		}

		return true;
	}

	/**
	 * 移除文件
	 * 
	 * @param rootDir
	 * @param fileName
	 */
	public static void removeFileByFileName(String rootDir, String fileName) {
		fileName = encodeByse64(fileName);

		if (!Utils.isSDCardEnable()) {
			return;
		}
		try {
			File file = new File(rootDir + fileName);
			if (file.exists()) {
				file.delete();
			}

		} catch (Exception e) {
		} finally {
		}

	}

	/**
	 * 
	 * 文件缓存
	 * <p>
	 * 
	 * @param rootDir
	 *            </p>
	 */
	public static void maintainCacheFile(String rootDir) {

		if (!Utils.isSDCardEnable()) {
			return;
		}

		try {
			File file = new File(rootDir);
			if (file.exists() && file.isDirectory()) {
				File[] files = file.listFiles();
				if (files.length > MAX_FILE_NUM) {
					Arrays.sort(files, new CompratorByLastModified());
					for (int i = 0, len = files.length - MAX_FILE_NUM / 2; i < len; i++) {
						// long time = files[i].lastModified();
						files[i].delete();
					}
				} else {
					long current = System.currentTimeMillis();
					Arrays.sort(files, new CompratorByLastModified());
					for (int i = 0, len = files.length / 5; i < len; i++) {
						long time = files[i].lastModified();
						if (current - time > DEFAULT_CACHE_TIME) {
							files[i].delete();
						}
					}
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}

	}

	/**
	 * 判断两个文件是否相同
	 * 
	 * @author
	 */
	private static class CompratorByLastModified implements Comparator<File> {
		public int compare(File f1, File f2) {
			long diff = f1.lastModified() - f2.lastModified();
			if (diff > 0)
				return 1;
			else if (diff == 0)
				return 0;
			else
				return -1;
		};

		public boolean equals(Object obj) {
			return true;
		};

	}

	/**
	 * 清楚所有文件
	 * 
	 * @param rootDir
	 */
	public static void clearFiles(String rootDir) {
		if (rootDir == null || rootDir.length() == 0) {
			return;
		}

		if (!Utils.isSDCardEnable()) {
			return;
		}

		File file = new File(rootDir);
		if (file.exists() && file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0, len = files.length; i < len; i++) {
				files[i].delete();
			}
		}
	}

	/**
	 * 返回ASCLL编码
	 * 
	 * @param name
	 * @return
	 */
	private static final String encodeByse64(String name) {
		try {
			return Base64.encode(name) + ".jpg";
		} catch (Exception e) {

		}
		return name;
	}

	/**
	 * 获取单个文件的大小
	 * 
	 * @param f
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public static long getFileSizes(File f) throws Exception {
		long s = 0;
		if (f.exists()) {
			FileInputStream fis = null;
			fis = new FileInputStream(f);
			s = fis.available();
		} else {
			Log.e("ggggg", "文件夹不存在");
		}
		return s;
	}

	/**
	 * 根据文件，获取文件总大小
	 * 
	 * @param f
	 * @return
	 * @throws Exception
	 */
	public static long getFileSize(File f) throws Exception {
		long size = 0;
		File flist[] = f.listFiles();
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getFileSize(flist[i]);
			} else {
				size = size + flist[i].length();
			}
		}
		return size;
	}

	/**
	 * 根据文件路径返回文件
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static String FormetFileSize(String filePath) throws Exception {
		File file = new File(filePath);
		long fileSize = CacheFileUtil.getFileSize(file);
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileSize == 0) {
			fileSizeString = 0 + "byte";
			return fileSizeString;
		} else if (fileSize < 1024) {
			fileSizeString = df.format((double) fileSize) + "byte";
			return fileSizeString;
		} else if (fileSize < 1048576) {
			fileSizeString = df.format((double) fileSize / 1024) + "Kb";
			return fileSizeString;
		} else if (fileSize < 1073741824) {
			fileSizeString = df.format((double) fileSize / 1048576) + "Mb";
			return fileSizeString;
		} else {
			fileSizeString = df.format((double) fileSize / 1073741824) + "Gb";
			return fileSizeString;
		}
	}

	/**
	 * 遍历获取文件列表
	 * 
	 * @param f
	 * @return
	 */
	public long getlist(File f) {
		long size = 0;
		File flist[] = f.listFiles();
		size = flist.length;
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getlist(flist[i]);
				size--;
			}
		}
		return size;

	}

}
